import ivr from '@/app/call-center/store/modules/ivr'
import { ElMessage } from 'element-plus'
import { cloneDeep, set } from 'lodash'
import { computed, nextTick, reactive, toRefs, watch } from 'vue'
export const isNumber2 = (str: string) => /^\d+$/.test(str)

const checkReplayTimes = (_: any, value: any, callback: (e?: any) => void) => {
  const boolean = new RegExp('^[0-9][0-9]*$').test(value)
  if (!boolean) {
    callback(new Error('请输入正整数'))
  } else if (value < 0 || value > 3) {
    callback(new Error('重播次数：0-3次'))
  } else {
    callback()
  }
}
const checkNumber = (_: any, value: any, callback: (e?: any) => void) => {
  const boolean = new RegExp('^[0-9][0-9]*$').test(value)
  if (!boolean) {
    callback(new Error('请输入正整数'))
  } else {
    callback()
  }
}
const checkReplayInterval = (_: any, value: any, callback: (e?: any) => void) => {
  const boolean = new RegExp('^[0-9][0-9]*$').test(value)
  if (!boolean) {
    callback(new Error('请输入正整数'))
  } else if (value < 1 || value > 10) {
    callback(new Error('重播间隔：1-10秒'))
  } else {
    callback()
  }
}

const timeOutNumber = (_: any, value: any, callback: (e?: any) => void) => {
  if (!isNumber2(value) || Number(value) <= 0 || Number(value) > 300) {
    callback(new Error('请输入1-300正整数'))
  } else {
    callback()
  }
}

type Props = {
  data: any
  currentNode: any
  nodeForm: any
  save: (...arg: any) => void
  cancel: () => void
  delete: (...arg: any) => void
}

type State = {
  originLen: number
  formData: any
  condition: any[]
  lineList: any[]
  nodeList: any[]
  currentData: any
  labelPosition: string
}

export default (props: Props) => {
  const IvrModule = ivr()
  const cache: any = IvrModule.selectCache
  const rules = {
    name: [{ required: true, message: '节点名称必填', trigger: 'change' }],
    text: [{ required: true, message: '合成文本必填', trigger: 'change' }],
    playType: [{ required: true, message: '放音类型必填', trigger: 'change' }],
    voice: [{ required: true, message: '语音文件必选', trigger: 'change' }],
    replayTimes: [{ required: true, trigger: 'change', validator: checkReplayTimes }],
    replayInterval: [{ required: true, trigger: 'change', validator: checkReplayInterval }],
    default: [{ required: true, message: '默认流转节点必填', trigger: 'change' }],
    callValue: [{ required: true, message: '数据必填', trigger: 'change' }],
    transferVoice: [{ required: true, message: '语音文件必选', trigger: 'change' }],
    voiceLibrary: [{ required: true, message: '语音文件必选', trigger: 'change' }],
    timeout: [{ required: true, trigger: 'change', validator: timeOutNumber }],
    engine: [{ required: true, message: '请选择服务厂商', trigger: 'change' }],
    voiceName: [{ required: true, message: '音色必选', trigger: 'change' }],
    requestTimeOut: [{ required: true, trigger: 'change', validator: checkNumber }],
    connectTimeOut: [{ required: true, trigger: 'change', validator: checkNumber }],
    responseTimeOut: [{ required: true, trigger: 'change', validator: checkNumber }]
  }
  const state: State = reactive({
    originLen: 0,
    formData: {},
    condition: [],
    lineList: [],
    nodeList: [],
    currentData: {},
    labelPosition: 'top'
  })

  const getConditionToId = (conditionId: any) => {
    let toId = ''
    state.lineList.some((item: any) => {
      if (item.from === conditionId) {
        toId = item.to
        return true
      }
    })
    return toId
  }

  // 处理定制条件参数的情况
  const customMadeValue = () => {
    // 初始化默认值
    if (props.currentNode.type === 'ivr-node-date') {
      state.formData.default = state.condition[state.condition.length - 1].to
      state.condition[state.condition.length - 1].value = 'default'
    }
    if (props.currentNode.type === 'ivr-node-dynamic-route' && !state.formData.routes) {
      state.formData.routes = [{ name: '分支1', operator: 'and', next: '', conditions: [{ k: '', op: '', v: '' }] }]
    }
  }

  const initNodeData = async () => {
    // 当前节点数据
    state.currentData = cloneDeep(props.currentNode)
    // 节点form数据
    state.formData = cloneDeep(props.currentNode.data)
    // 节点连线关系
    state.lineList = cloneDeep(props.data.lineList)
    // 当前ivr所有节点
    state.nodeList = cloneDeep(props.data.nodeList)
    // 原始条件数量
    state.originLen = state.currentData.condition.length
    state.currentData.condition.forEach((item: any, index: number) => {
      const conId = state.currentData.id + '-' + index
      const to = getConditionToId(conId)
      state.condition.every((i: any) => i.label !== item.label) &&
        state.condition.push({
          id: conId,
          label: item.label,
          value: item.value,
          to,
          customValue: item.customValue || ''
        })
    })
    await nextTick()
    customMadeValue()
  }

  watch(
    () => props,
    () => initNodeData(),
    {
      deep: true,
      immediate: true
    }
  )

  const getNodeList = () => {
    state.nodeList = cloneDeep(props.data.nodeList)
  }

  const onSubmit = async () => {
    getNodeList()
    try {
      await props.nodeForm.value.validate()
      console.log(state.condition, state.currentData)
      if (state.condition.length > 0) {
        state.condition.forEach((item: any, index: number) => {
          state.condition[index].id = state.currentData.id + '-' + index
        })
      }
      if (state.currentData.type === 'ivr-node-start') {
        if (state.formData.customList.length > 1) {
          const flag = state.formData.customList.find((i: any) => !i.key)
          if (flag) {
            ElMessage.warning('有参数未添加, 请检查')
            return
          }
        }
      }
      if (state.currentData.type === 'ivr-node-callurl') {
        const flag = state.formData.variableList.find((i: any) => !i.key)
        if (flag) {
          ElMessage.warning('有参数未选择, 请检查')
          return
        }
      }

      state.currentData.condition = state.condition
      state.currentData.data = state.formData
      state.nodeList.some((item: any, index: number) => {
        if (item.id === state.currentData.id) {
          state.nodeList[index] = state.currentData
          return true
        }
      })
      state.condition = state.condition.filter((i: any) => i.id)
      props.save(state.condition, state.nodeList, state.originLen, state.currentData.id)
    } catch (error) {
      console.log(error)
    }
  }

  const cancel = () => {
    props.cancel()
  }

  const deleteNode = () => {
    props.delete(state.currentData)
  }

  // 删除某个条件
  const deleteCondition = (_: any, index: number) => {
    if (state.condition.length > 1) {
      state.condition.splice(index, 1)
    }
  }

  const validateForm = () => {
    props.nodeForm.value.validate()
  }

  const voiceLibraryList: any = computed(() => {
    return cache.voiceLibraryList
      .filter((i: any) => i.voiceType === 'general_voice' && i.status === 'pass')
      .map((i: any) => ({ ...i, label: i.name, value: i.id }))
  })

  const timeConditionList = computed(() => {
    return cache.timeConditionList.map((i: any) => ({ ...i, label: i.name, value: i._id }))
  })

  const queueList = computed(() => {
    return cache.queueList.map((i: any) => ({ ...i, label: i.name, value: i.groupNumber }))
  })

  const userList = computed(() => {
    return cache.userList.map((i: any) => ({ ...i, label: i.name, value: i._id }))
  })

  const currentVoice = computed(() => {
    let currentVoice = {}
    voiceLibraryList.value.some((item: any) => {
      if (item.id === state.formData.voice || item.id === state.formData.transferVoice) {
        currentVoice = item
      }
    })
    return currentVoice
  })

  const changeState = (key: string, value: any) => {
    set(state, key, value)
  }
  return {
    rules,
    getConditionToId,
    customMadeValue,
    initNodeData,
    getNodeList,
    onSubmit,
    cancel,
    deleteNode,
    deleteCondition,
    validateForm,
    voiceLibraryList,
    timeConditionList,
    queueList,
    userList,
    currentVoice,
    changeState,
    ...toRefs(state)
  }
}
